package com.fly.demo.controller;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/data")
public class DataController
{
    private Resource[] resources;
    
    @PostConstruct
    private void init()
        throws IOException
    {
        resources = new PathMatchingResourcePatternResolver().getResources("classpath:pic/**/*.jpg");
    }
    
    /**
     * 返回字节数组不可使用注解@Controller，返回值会被当作视图路径解析导致异常
     * 
     * @return
     */
    @GetMapping(value = "/pic1", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] showPic1()
        throws IOException
    {
        int index = RandomUtils.nextInt(0, resources.length);
        Resource resource = resources[index];
        return IOUtils.toByteArray(resource.getInputStream());
    }
    
    @GetMapping(value = "/pic2", produces = MediaType.IMAGE_JPEG_VALUE)
    public void showPic2(HttpServletResponse response)
        throws IOException
    {
        int index = RandomUtils.nextInt(0, resources.length);
        Resource resource = resources[index];
        IOUtils.copy(resource.getInputStream(), response.getOutputStream());
    }
    
    @GetMapping(value = "/down", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void down(HttpServletResponse response)
        throws IOException
    {
        List<Path> filePaths = new ArrayList<>();
        Stream.of(new ClassPathResource("pic").getFile().listFiles()).forEach(lib -> filePaths.add(lib.toPath()));
        // 压缩多个文件到zip文件中
        String filename = DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMddHHmmss");
        response.setHeader("Content-Disposition", "attachment;filename=imgs_" + filename + ".zip");
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream()))
        {
            for (Path path : filePaths)
            {
                try (InputStream inputStream = Files.newInputStream(path))
                {
                    zipOutputStream.putNextEntry(new ZipEntry(path.getFileName().toString()));
                    StreamUtils.copy(inputStream, zipOutputStream);
                    zipOutputStream.flush();
                }
            }
        }
    }
}